package com.hong;

import com.hong.qrpc.factory.QrpcThreadFactory;
import com.hong.qrpc.spring.springboot.starter.annotation.EnableQrpcClient;
import com.hong.service.CalcService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * qrpc-spring-boot-starter的客户端，只需要添加EnableQrpcClient注解并且在配置文件中提供注册中心的地址就可以实现注册
 * (配置文件由spring进行扫描，无需额外添加配置文件)
 *
 * @Author HQT
 * @Date 2022/7/31 9:48
 */
@EnableQrpcClient(basePackages = {"com.hong"})
@SpringBootApplication
public class Client {
    @Autowired
    private CalcService calcService;

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Client.class, args);
        Client bean = context.getBean(Client.class);
        CalcService calcService = bean.calcService;
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(16, 16, 1000, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10000), new QrpcThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
        long before = System.currentTimeMillis();
        //计数器确认其是否完整响应了所有请求
        AtomicInteger atomicInteger = new AtomicInteger();
        for (int i = 0; i < 10000; i++) {
            poolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(calcService.add(100, 50) + "  end time:" + (System.currentTimeMillis() - before));
//                    System.out.println("start time:" + (System.currentTimeMillis()) + "  data:" + calcService.getMixedMap() + "  end time:" + (System.currentTimeMillis() - before) + "  requestId" + atomicInteger.getAndIncrement());
                }
            });
        }
//        try {
//            Thread.sleep(10000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        System.out.println(atomicInteger);
    }
}
